package com.nuatar.meibi.scoll;

import android.graphics.PointF;
import android.util.FloatMath;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;

public class ZoomListener implements OnTouchListener {
	float Ospace;
	PointF start = new PointF(0, 0);
	String Mode;
	private Swiper swp;
	
	public ZoomListener(Swiper ssw){
		swp=ssw;
	}
	@Override
	public boolean onTouch(View v, MotionEvent event) {
		// TODO 自动生成的方法存根

		switch (event.getAction() & MotionEvent.ACTION_MASK) {
		case MotionEvent.ACTION_DOWN:
			start.set(event.getX(), event.getY());
		
			Mode = "DRAG";
			break;
		case MotionEvent.ACTION_POINTER_DOWN:
			Ospace = spacing(event);
			Mode = "ZOOM";
			

			break;
		case MotionEvent.ACTION_UP:
		case MotionEvent.ACTION_POINTER_UP:
			Mode = "NONE";
			
			if(((MyXZ) v).getZoom() == 1){
				float sx = start.x - event.getX();
				float sy = start.y - event.getY();
				if (Math.abs(sx) > Math.abs(sy)) {
					swp.Swipe(v, sx);
				}
			}
			start.set(event.getX(), event.getY());
			break;
		case MotionEvent.ACTION_MOVE:
			if (Mode == "DRAG") {
				if (((MyXZ) v).getZoom() > 1) {
					float sx = start.x - event.getX();
					float sy = start.y - event.getY();
					if(Math.sqrt(sx*sx+sy*sy)>5){
					((MyXZ) v).setPan((int) (start.x - event.getX()),
							(int) (start.y - event.getY()));
					start.set(event.getX(), event.getY());
					}
				}
			
				

			} else if (Mode == "ZOOM") {
				float nspace = spacing(event);
				float zoom = 1 + (nspace - Ospace) / Ospace;
					if(Math.abs(nspace - Ospace)>3){
					((MyXZ) v).setZoom(zoom);
					Ospace=nspace;
					}
				
			}
			break;
	
		}
		return true;
	}

	private float spacing(MotionEvent event) {
		float x = event.getX(0) - event.getX(1);
		float y = event.getY(0) - event.getY(1);
		return FloatMath.sqrt(x * x + y * y);
	}

	public Swiper getSwp() {
		return swp;
	}

	public void setSwp(Swiper swp) {
		this.swp = swp;
	}

	public interface Swiper {
		public void Swipe(View v, float length);
	}
	
}
